import datetime

from flask import Blueprint, request, jsonify
from flask_apscheduler import APScheduler

job_index = Blueprint('job_index', __name__)
job_index.url_prefix = '/job'

scheduler = APScheduler()
scheduler.start()


def task1(a, b):
    print('mission_1_', a, b)
    print(datetime.datetime.now())


def task2(a, b):
    print('mission_2_', a, b)

    print(datetime.datetime.now())


@job_index.route('/pause', methods=['GET'])
def pause_job():  # 暂停
    job_id = request.args.get('id')
    scheduler.pause_job(str(job_id))
    return "pause success!"


@job_index.route('/resume', methods=['GET'])
def resume_job():  # 恢复
    job_id = request.args.get('id')
    scheduler.resume_job(str(job_id))
    return "Success!"


@job_index.route('/get_jobs', methods=['GET'])
def get_task():  # 获取
    # job_id = request.args.get('id')
    jobs = scheduler.get_jobs()
    return jsonify(len(jobs))


@job_index.route('/remove_job', methods=['GET'])
def remove_job():  # 移除
    job_id = request.args.get('id')
    scheduler.remove_job(str(job_id))
    return 'remove success'


# /add_job?id=2
@job_index.route('/add_job', methods=['GET'])
def add_task():
    data = request.args.get('id')
    if data == '1':
        # trigger='cron' 表示是一个定时任务
        scheduler.add_job(func=task1, id='1', args=(1, 1), trigger='cron', day_of_week='0-6', hour=21, minute=25,
                          second=00, replace_existing=True)
    else:
        # trigger='interval' 表示是一个循环任务，每隔多久执行一次
        scheduler.add_job(func=task2, id='2', args=(2, 2), trigger='interval', seconds=10,
                          replace_existing=True)
    return 'sucess'
